package com.dxyxx.framework;

import java.io.IOException;

import org.apache.http.Header;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.JavaType;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import br.com.pierry.simpletoast.SimpleToast;

import com.dxyxx.R;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.framework.CAS.CallBack;
import com.dxyxx.pojo.PayType;
import com.dxyxx.pojo.ResponseResult;
import com.dxyxx.pojo.Ticket;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ta.utdid2.android.utils.StringUtils;

public class BuyTicketActivity extends BaseActivity {
	private ImageView checkout_1;
	private ImageView checkout_2;
	private boolean wechat = true;
	private double discount = 0.98;
	private TextView finalMoney;
	private ProgressDialog progressDialog;
	private String finalAmount = "0.00";
	private EditText txtInput;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_buyticket);
		initViews();
		// 发出请求，得到 折扣，

	}

	private void initViews() {

		((LinearLayout) findViewById(R.id.ecardLayout)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				CAS call = new CAS(BuyTicketActivity.this, RequestCode.MyQr2, new CallBack() {
					@Override
					public void method() {
						startActivity(new Intent(BuyTicketActivity.this, ScanActivity.class));
					}
				});
				call.call();
			}

		});

		((ImageView) findViewById(R.id.backImageButton)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		checkout_1 = (ImageView) findViewById(R.id.checkbox_1);
		checkout_1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (!wechat) {
					checkout_1.setImageResource(R.drawable.check01);
					checkout_2.setImageResource(R.drawable.check02);
					wechat = !wechat;
				}
			}
		});
		checkout_2 = (ImageView) findViewById(R.id.checkbox_2);
		checkout_2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (wechat) {
					checkout_2.setImageResource(R.drawable.check01);
					checkout_1.setImageResource(R.drawable.check02);
					wechat = !wechat;
				}
			}
		});
		finalMoney = (TextView) findViewById(R.id.finalMoney);
		// Edittext 输入的数字只能是999.99-0.01之间，只能是数字和小数点
		txtInput = (EditText) findViewById(R.id.txtInput);
		// 获取焦点
		txtInput.setFocusable(true);
		txtInput.setFocusableInTouchMode(true);
		txtInput.requestFocus();
		txtInput.requestFocusFromTouch();
		txtInput.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable edt) {
				String temp = edt.toString();
				int posDot = temp.indexOf(".");
				if (posDot <= 0) {
					if (temp.length() <= 4) {
						if (!StringUtils.isEmpty(edt.toString())) {
							finalAmount = df.format(Double.parseDouble(edt.toString()) * discount);
							finalMoney.setText("￥" + finalAmount);
						}
						return;
					} else {
						edt.delete(4, 5);
						if (!StringUtils.isEmpty(edt.toString())) {
							finalAmount = df.format(Double.parseDouble(edt.toString()) * discount);
							finalMoney.setText("￥" + finalAmount);
						}
						return;
					}
				}
				if (temp.length() - posDot - 1 > 2) {
					edt.delete(posDot + 3, posDot + 4);
				}
				//设置 打折之后 的情况。
				if (!StringUtils.isEmpty(edt.toString())) {
					finalAmount = df.format(Double.parseDouble(edt.toString()) * discount);
					finalMoney.setText("￥" + finalAmount);
				}
			}

			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}

			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}
		});
		((ImageView) findViewById(R.id.nextImageButton)).setVisibility(View.INVISIBLE);
		TextView title = (TextView) findViewById(R.id.title);
		title.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
		title.setText("代金券");

		findViewById(R.id.buy).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if ("0.00".equals(finalAmount)) {
					SimpleToast.error(BuyTicketActivity.this, "请输入金额");
					return;
				}

				// 等待框架
				progressDialog = ProgressDialog.show(BuyTicketActivity.this, null, null);
				progressDialog.setContentView(R.layout.dialog_circle);
				// 每次 退出之后都要重新获取token。 这时候 要重新登录，处理 失效的情况。
				String urlString = "order/addTicket";
				RequestParams params = new RequestParams();
				params.add("description", "代金券");
				if (wechat) {
					params.add("payType", "tenpay");
				} else {
					params.add("payType", "alipay");
				}
				params.add("deliveryType", "自提");
				params.add("storeId", "1");
				params.add("money", txtInput.getText().toString());// 应该是输进去的值
				//				String orderDetails;
				try {
					HttpUtil.post(urlString, params, new AsyncHttpResponseHandler() {

						@Override
						public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
							AgainPlayer.makeCall(BuyTicketActivity.this, "网络好像出错了");
						}

						@Override
						public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
							// 登陆失效 返回的信息 {"code":-1,"info":"没有登陆","object":null}
							try {
								ResponseResult rr = getObjectMapper().readValue(new String(arg2), ResponseResult.class);
								if (rr.getCode() == -1) { // 传递。重登陆
									Intent intent = new Intent(BuyTicketActivity.this, LoginActivity.class);
									intent.putExtra("relogin", true);
									Toast.makeText(BuyTicketActivity.this, " 重新获取token", 0).show();
									startActivityForResult(intent, RequestCode.BuyTicket2);

								} else if (rr.getCode() == 0) { // 传递
									Toast.makeText(BuyTicketActivity.this, rr.getInfo(), 0).show();

								} else {
									Toast.makeText(BuyTicketActivity.this, "token正常", 0).show();
									// 成功 了 处理订单
									doWithOrder(new String(arg2));
								}
							} catch (JsonParseException e) {
								e.printStackTrace();
							} catch (JsonMappingException e) {
								e.printStackTrace();
							} catch (IOException e) {
								e.printStackTrace();
							}

						}

						public void onFinish() {
							progressDialog.dismiss();
						};

					});
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});

	}

	private void doWithOrder(String responseStr) {

		try {
			JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, Ticket.class);
			//报错如下：
			// org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class  com.dxyxx.pojo.User]: can not instantiate from JSON object (need to add/enable type information?)  
			// 解决方法： 为User增加一个无参构造函数
			ResponseResult<Ticket> result = getObjectMapper().readValue(new String(responseStr), javaType);
			if (result.getCode() == 1) {
				Bundle bundle = new Bundle();
				// Order要实现implements Serializable ，Order 的User成员变量也要实现implements Serializable 
				bundle.putSerializable("ticket", result.getObject());
				Intent intent = new Intent(BuyTicketActivity.this, Pay2Activity.class);
				intent.putExtras(bundle);
				startActivity(intent);
			} else {
				Toast.makeText(BuyTicketActivity.this, result.getInfo(), 0).show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 重新登录 得到token
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == RequestCode.MyQr2) {
			startActivity(new Intent(BuyTicketActivity.this, ScanActivity.class));
			return;
		}
		if (requestCode == RequestCode.BuyTicket2) {
			if (data != null) {
				String result = data.getExtras().getString("result");

				Toast.makeText(BuyTicketActivity.this, "token 已更新", 0).show();
				String urlString = "order/addTicket";
				RequestParams params = new RequestParams();
				params.add("description", "代金券");
				if (wechat) {
					params.add("payType", "tenpay");
				} else {
					params.add("payType", "alipay");
				}
				params.add("deliveryType", "自提");
				params.add("storeId", "1");
				params.add("money", finalAmount);

				HttpUtil.post(urlString, params, new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
						AgainPlayer.makeCall(BuyTicketActivity.this, "网络好像出错了");
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
						try {
							ResponseResult rr = getObjectMapper().readValue(new String(arg2), ResponseResult.class);
							if (rr.getCode() == 0) {
								Toast.makeText(BuyTicketActivity.this, rr.getInfo(), 0).show();
							} else {
								doWithOrder(new String(arg2));
							}
						} catch (JsonParseException e) {
							e.printStackTrace();
						} catch (JsonMappingException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

					public void onFinish() {
						progressDialog.dismiss();
					};

				});

			}

		}
	}

}
